% function calculate the residual between
% a measured channel and it's prediction
% to be used with robust routines
% derived from cohe.m
% latest date 11.03.2003


function[E] = r_resid(tf1,data,flag),


% a & b are corresponding impedance (Zxx Zxy) or (Zyx Zyy)
% data is array of cross spectra - SPMmatrix
% 
%flag should be either 'Ex' or 'Ey';

if flag == 'Ex',
   a = tf1(3);
   b = tf1(1);
elseif flag == 'Ey',
   a = tf1(2);
   b = tf1(4);
end;


j = sqrt(-1);

HxHx = data(1,1);
HyHy = data(2,2);
HzHz = data(3,3);
ExEx = data(4,4);
EyEy = data(5,5);

HxHy = data(2,1) - j*data(1,2);
HyHx = conj(HxHy);
HxEx = data(4,1) - j*data(1,4);
ExHx = conj(HxEx);
HxEy = data(5,1) - j*data(1,5);
EyHx = conj(HxEy);
ExHy = data(4,2) + j*data(2,4);
HyEx = conj(ExHy);
HyEy = data(5,2) - j*data(2,5);
EyHy = conj(HyEy);



ZpX = a*HxHx + b*HyHx;
ZpY = a*HxHy + b*HyHy;

%ZpZp = a XZp + b YZp = a (ZpX) + b (ZpY) ;

ZpZp = a*conj(ZpX) + b*conj(ZpY);


if flag == 'Ex',
   E = ZpZp-ExEx; %removed abs on 7.4.3
elseif flag == 'Ey',
	E = ZpZp-EyEy;
end;

